package com.martin.lib_base.utils

import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import java.util.concurrent.ConcurrentHashMap

/**
 * @author：孟凡华
 * @date：2022/12/1
 * @desc：
 */
object FlowBus {

    // 总线map
    private val busMap = ConcurrentHashMap<Any, MutableSharedFlow<Any>>()

    // 粘性事件总线map
    private val busStickyMap = ConcurrentHashMap<Any, MutableSharedFlow<Any>>()

    /**
     * 根据Key获取事件总线
     */
    fun <T> with(key: String): MutableSharedFlow<T> {
        if (!busMap.containsKey(key)) {
            busMap[key] = MutableSharedFlow(0, 1, BufferOverflow.DROP_OLDEST)
        }
        return busMap[key] as MutableSharedFlow<T>
    }

    /**
     * 根据Key获取事件总线
     * 粘性事件需要发送及接收都使用才奏效
     */
    fun <T> withSticky(key: String): MutableSharedFlow<T> {
        if (!busStickyMap.containsKey(key)) {
            busStickyMap[key] = MutableSharedFlow(1, 1, BufferOverflow.DROP_OLDEST)
        }
        return busStickyMap[key] as MutableSharedFlow<T>
    }

}